package com.net0110.codeaide.util;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;

import java.util.*;

/**
 * @author alon
 * @date 2022/7/27
 * @Desc CRMEB 代码生成器
 *  Controller 生成目录由应用分组决定(默认为 crmeb-front, 自动生成分组路由)
 *  Model 固定生成在 crmeb-common 应用下
 *  Service、Dao、Xml 固定生成在 crmeb-service 应用下
 *  重新生成只更新 Model 文件
 */
public class CodeAide {
    /**
     * 项目路径
     */
    private static final String PARENT_DIR = System.getProperty("user.dir");
    /**
     * 基本路径
     */
    // private static final String SRC_MAIN_JAVA = "/src/main/java/";
    /**
     * xml路径 （crmeb mapper）
     */
    private static final String XML_PATH = PARENT_DIR + "/crmeb-service/src/main/resources/mapper";
    /**
     * entity路径 (crmeb model)
     */
    private static final String ENTITY_PATH = PARENT_DIR + "/crmeb-common/src/main/java/com/zbkj/common/model";
    /**
     * mapper路径 （crmeb dao）
     */
    private static final String MAPPER_PATH = PARENT_DIR + "/crmeb-service/src/main/java/com/zbkj/service/dao";
    /**
     * service路径
     */
    private static final String SERVICE_PATH = PARENT_DIR + "/crmeb-service/src/main/java/com/zbkj/service/service";
    /**
     * serviceImpl路径
     */
    private static final String SERVICE_IMPL_PATH = PARENT_DIR + "/crmeb-service/src/main/java/com/zbkj/service/service/impl/";
    /**
     * controller路径
     */
    private static final String CONTROLLER_PATH = PARENT_DIR + "/crmeb-front/src/main/java/com/zbkj/front/controller";
    /**
     * 数据库url
     */
    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/fenggou_c";
    /**
     * 数据库用户名
     */
    private static final String USERNAME = "root";
    /**
     * 数据库密码
     */
    private static final String PASSWORD = "123456";

    // 应用名称
    private static String GROUP_NAME = "";

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 要构建代码的表名
        GROUP_NAME = scanner("应用分组(默认:front)");
        String moduleName = scanner("模块名");
        String[] tables = scanner("表名(包括前缀)").split(",");

        FastAutoGenerator.create(DB_URL, USERNAME, PASSWORD)
                // 全局配置
                .globalConfig(
                        builder -> builder
                                .author("Alon")
                                .disableOpenDir()
                                .commentDate("yyyy-MM-dd HH:mm:ss")
                                .dateType(DateType.ONLY_DATE)
                                .enableSwagger()
                )
                // 包配置
                .packageConfig(
                        builder -> builder
                                .parent("com.zbkj")
                                //.moduleName(moduleName)
                                .controller( moduleName + ".controller")
                                .entity("common.model")
                                .mapper("service.dao")
                                .service("service.service")
                                .serviceImpl("service.service.impl")
                                .xml("mapper")
                                .pathInfo(getPathInfo())
                )
                // 策略配置
                .strategyConfig(
                        builder -> builder
                                .addTablePrefix("eb_")
                                .addInclude(tables)
                                .entityBuilder()
                                    .fileOverride() // 允许覆盖
                                    .naming(NamingStrategy.underline_to_camel)
                                    .columnNaming(NamingStrategy.underline_to_camel)
                                    .enableChainModel() // 开启链式模型
                                    // .enableActiveRecord()   // 开启 ActiveRecord 模型
                                    // .formatFileName("%sModel")
                                    .enableLombok()
                                .controllerBuilder()
                                    .formatFileName("%sController")
                                    .enableHyphenStyle()
                                    .enableRestStyle()
                               //   .superClass("com.xxx.BaseController") //父类
                                .serviceBuilder()
                                    .formatServiceFileName("%sService")
                                    .formatServiceImplFileName("%sServiceImpl")
                                .mapperBuilder()
                                    //.fileOverride() // 允许覆盖
                                    //.enableBaseResultMap()
                                    //.enableBaseColumnList()
                                    .superClass(BaseMapper.class)
                                    .formatMapperFileName("%sDao")
                                    .enableMapperAnnotation()
                )
                // 模板配置
                .templateConfig(
                        builder -> builder
                                .controller("/templates/controller.java.vm")
                                .service("/templates/service.vm")
                                .serviceImpl("/templates/service.impl.vm")
                )
                .injectionConfig(
                        builder -> builder
                                .customMap(Collections.singletonMap("GroupName", GROUP_NAME))
                )
                .execute();
    }
    public static void main2(String[] args) {
        // 要构建代码的表名
        String[] tableNames = {"eb_exchange"};

        FastAutoGenerator.create(DB_URL, USERNAME, PASSWORD)
                // 全局配置
                .globalConfig(builder -> builder
                        .author("Alon")
                        .disableOpenDir()
                        .commentDate("yyyy-MM-dd")
                        .enableSwagger()
                )
                // 包配置
                .packageConfig(builder -> builder
                        .parent("com.zbkj")
                        .xml("mapper")
                        .entity("model")
                        .mapper("dao")
                        .service("service")
                        .serviceImpl("service.impl")
                        .controller("controller")
                        .pathInfo(getPathInfo())
                )
                // 策略配置
                .strategyConfig(builder -> builder
                        .addInclude(tableNames)
                        // entity
                        .entityBuilder()
                        .fileOverride()
                        .enableChainModel()
                        .fileOverride()
                        .enableLombok()
                        .enableRemoveIsPrefix()
                        .logicDeleteColumnName("is_delete")
                        .idType(IdType.ASSIGN_ID)
                        .addTableFills(new Column("create_time", FieldFill.INSERT))
                        .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
                        // controller
                        .controllerBuilder()
                        .fileOverride()
                        .enableRestStyle()
                        .formatFileName("%sController")
                        // service
                        .serviceBuilder()
                        .fileOverride()
                        .superServiceClass(IService.class)
                        .formatServiceFileName("%sService")
                        .formatServiceImplFileName("%sServiceImp")
                        // mapper
                        .mapperBuilder()
                        .fileOverride()
                        .enableBaseResultMap()
                        .enableBaseColumnList()
                        .superClass(BaseMapper.class)
                        .formatMapperFileName("%sDao")
                        .formatXmlFileName("%sXml")
                        .enableMapperAnnotation()
                )
                .execute();
    }

    /**
     * 获取路径信息map
     *
     * @return {@link Map< OutputFile, String> }
     * @author MK
     * @date 2022/4/21 21:21
     */
    private static Map<OutputFile, String> getPathInfo() {
        Map<OutputFile, String> pathInfo = new HashMap<>(5);
        pathInfo.put(OutputFile.entity, ENTITY_PATH);
        pathInfo.put(OutputFile.mapper, MAPPER_PATH);
        pathInfo.put(OutputFile.service, SERVICE_PATH);
        pathInfo.put(OutputFile.serviceImpl, SERVICE_IMPL_PATH);

        if(StringUtils.isEmpty(GROUP_NAME)){
            pathInfo.put(OutputFile.controller, CONTROLLER_PATH);
        }else{
            // 自定义应用分组, 按目录生成生成
            pathInfo.put(OutputFile.controller, PARENT_DIR + "/crmeb-" + GROUP_NAME + "/src/main/java/com/zbkj/" + GROUP_NAME + "/controller");
        }
        pathInfo.put(OutputFile.xml, XML_PATH);
        return pathInfo;
    }
}
